import React, { useState } from 'react';
import { OrderParams } from '@/type/ConsultOrder';
import { OrderItem as OrderType } from '@/type/ConsultOrder';
import { fetchOrderList } from '@/store/modules/consultStore';
import { InfiniteScroll, Toast } from 'antd-mobile';
import { useEnhanceDispatch } from '@/hooks';
import OrderItem from '@/views/ConsultType/ConsultOrder/components/OrderItem/OrderItem';
import { OrderType as OrderTypeEnum } from '@/enum';
import './OrderList.scss';

interface OrderListProps {
  type: '1' | '2' | '3';
}

const OrderList: React.FunctionComponent<OrderListProps> = ({ type }) => {
  const enhanceDispatch = useEnhanceDispatch();
  // 是否加载完毕
  const [hasMore, setHasMore] = useState(true);
  // 获取订单列表的参数
  const [params, setParams] = useState<OrderParams>({ current: 1, pageSize: 10, type });
  // 订单列表
  const [orderList, setOrderList] = useState<OrderType[]>([]);
  // 订单列表总数
  const [total, setTotal] = useState(0);

  /**
   * @description 获取订单列表的回调函数
   * */
  const fetchOrder = async () => {
    try {
      const { rows, total } = await enhanceDispatch(fetchOrderList(params)).unwrap();
      setTotal(total);
      setOrderList([...orderList, ...rows]);
      setParams({ ...params, current: params.current += 1 });
      if (orderList.length >= total) {
        setHasMore(false);
      }
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };


  /**
   *删除订单的回调函数(子组件调用)
   * */
  const deleteOrder = (id: string) => {
    const filterOrderList = orderList.filter(item => item.id !== id);
    setOrderList(filterOrderList);
  };

  /**
   *取消问诊的回调函数(子组件调用)
   * */
  const cancelOrder = (id: string) => {
    const order = orderList.find(item => item.id == id) as OrderType;
    order.status = OrderTypeEnum.ConsultCancel;
    setOrderList([...orderList]);
  };

  return (
    <div className="order-list">
      {
        orderList.map((order, index) => <OrderItem order={order} key={index} cancelSuccess={cancelOrder} deleteSuccess={deleteOrder}></OrderItem>)
      }
      <InfiniteScroll loadMore={fetchOrder} hasMore={hasMore} />
    </div>
  );
};

export default OrderList;